/*
 * @Author: aggfb 714740235@qq.com
 * @Date: 2024-04-18 23:03:19
 * @LastEditors: aggfb 714740235@qq.com
 * @LastEditTime: 2024-05-21 22:06:11
 * @FilePath: \stepper_motor\control\hw_elec.c
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
/*****
  ** @file     : hw_elec.c/h
  ** @brief    : 硬件电流控制器
  ** @versions : 2.1.2
  ** @time     : 2020/08/08
  ** @reviser  : unli (HeFei China)
  ** @explain  : null
*****/

#include "hw_elec.h"
#include "sin_form.h"
#include "bsp_gpio.h"

/* 硬件电流实例 */
static coil_t coil_a;
static coil_t coil_b;

/**
  * @brief  12位基准电压混合输出
  * @param  elec_va: 电流通道a基准
  * @param  elec_vb: 电流通道b基准
  * @retval NULL
  */
static void hw_elec_current_control_vref(uint16_t elec_va, uint16_t elec_vb)
{
	BSP_DAC_OUT0_SET_VAL((elec_va >> 2));
	BSP_DAC_OUT1_SET_VAL((elec_vb >> 2));
}

/**
  * @brief  设置睡眠
  * @param  NULL
  * @retval NULL
  */
void hw_elec_set_sleep(void)
{
	hw_elec_current_control_vref(0, 0);
	BSP_GPIO_WINDING_AP_SET(0);
	BSP_GPIO_WINDING_AN_SET(0);
	BSP_GPIO_WINDING_BP_SET(0);	
	BSP_GPIO_WINDING_BN_SET(0);
}

/**
  * @brief  设置驱动刹车
  * @param  NULL
  * @retval NULL
  */
void hw_elec_set_brake(void)
{
	coil_a.dac_reg = 0;
	coil_b.dac_reg = 0;
	hw_elec_current_control_vref(0, 0);
	BSP_GPIO_WINDING_AP_SET(1);
	BSP_GPIO_WINDING_AN_SET(1);
	BSP_GPIO_WINDING_BP_SET(1);	
	BSP_GPIO_WINDING_BN_SET(1);
}

/**
  * @brief  设置输出细分电流
  * @param  divide:  细分 (0 ~ 细分数)
  * @param  dac_reg: 电流 (0 ~ 3300mA)
  * @retval NULL
  */
void hw_elec_set_divide_current(uint32_t divide, int32_t elec_ma)
{
	//由细分数获得数组指针
	coil_b.conver = (divide) & (0x000003FF);								//对1024取余
	coil_a.conver = (coil_b.conver + (256)) & (0x000003FF);	//对1024取余
	
	//由数据指针获得整形数据(空间换时间方案)
	coil_a.sin_data = sin_pi_m2[coil_a.conver];
	coil_b.sin_data = sin_pi_m2[coil_b.conver];

	//由整形数据获得DAC寄存器数据
	uint32_t dac_reg = abs(elec_ma);								//电压电流关系为1:1(检流电阻为0.1欧)
	dac_reg = (uint32_t)(dac_reg * 5083) >> 12; 		//(dac_reg * 4095 / 3300)的变种
	dac_reg = dac_reg & (0x00000FFF);								//(对4096取余)(向小取整)(舍弃符号位)
	coil_a.dac_reg = (uint32_t)(dac_reg * abs(coil_a.sin_data)) >> sin_pi_m2_dpiybit;	//(--- / sin_1024_dpiy)的变种
	coil_b.dac_reg = (uint32_t)(dac_reg * abs(coil_b.sin_data)) >> sin_pi_m2_dpiybit;	//(--- / sin_1024_dpiy)的变种

	//DAC输出
	hw_elec_current_control_vref(coil_a.dac_reg, coil_b.dac_reg);
	if(coil_a.sin_data > 0)				
	{	
		BSP_GPIO_WINDING_AP_SET(1);		
		BSP_GPIO_WINDING_AN_SET(0);		
	}
	else if(coil_a.sin_data < 0)	
	{	
		BSP_GPIO_WINDING_AP_SET(0);		
		BSP_GPIO_WINDING_AN_SET(1);		
	}
	else 													
	{	
		BSP_GPIO_WINDING_AP_SET(1);
		BSP_GPIO_WINDING_AN_SET(1);
	}
	if(coil_b.sin_data > 0)				
	{	
		BSP_GPIO_WINDING_BP_SET(1);		
		BSP_GPIO_WINDING_BN_SET(0);		
	}
	else if(coil_b.sin_data < 0)	
	{	
		BSP_GPIO_WINDING_BP_SET(0);		
		BSP_GPIO_WINDING_BN_SET(1);		
	}
	else													
	{	
		BSP_GPIO_WINDING_BP_SET(1);	
		BSP_GPIO_WINDING_BN_SET(1);
	}
}
